package cn.ffcs.uec.staffAndOutStaff.component;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.web.servlet.Servlets;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Div;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import cn.ffcs.uec.staffAndOutStaff.component.bean.StaffTotalInfoListboxExtBean;
import cn.ffcs.uec.staffAndOutStaff.manager.StaffAndOutStaffManager;
import cn.ffcs.uec.staffAndOutStaff.vo.StaffTotalInfo;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.ExportExcelNew;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.vo.PageInfo;
import lombok.Getter;
import lombok.Setter;

/**
 * 人员信息总表
 * 
 * @Title:
 * @Description:
 * @author Wang Yiren
 * @版权 FFCS（C） 2017
 * @date 2018年9月30日
 */
@Controller
@Scope("prototype")
public class StaffTotalInfoListboxExt extends Div implements IdSpace {

    private static final long serialVersionUID = -885448835759987759L;

    private static final String STAFF_AND_OUTSTAFF_ZUL = "/pages_nmg/staffAndOutStaff/comp/staffTotalInfo_listbox_ext.zul";

    private StaffTotalInfoListboxExtBean bean = new StaffTotalInfoListboxExtBean();

    private StaffTotalInfo staffTotalInfo = new StaffTotalInfo();

    private StaffAndOutStaffManager staffAndOutStaffManager = (StaffAndOutStaffManager) ApplicationContextUtil
            .getBean("staffAndOutStaffManager");

    List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

    @Getter
    @Setter
    private IPortletInfoProvider portletInfoProvider;

    public StaffTotalInfoListboxExt() {
        Executions.createComponents(STAFF_AND_OUTSTAFF_ZUL, this, null);
        Components.wireVariables(this, bean);
        Components.addForwards(this, this, '$');
        // 转发
        //this.addForward("onOrgTreeStaffAndOutStaffQuery", this, "onOrgTreeStaffAndOutStaffQueryResponse");
    }

    /**
     * 界面初始化
     */
    public void onCreate() {
    }

    /**
     * 监听组织树抛出的事件
     * 
     * @param event
     */
//    public void onOrgTreeStaffAndOutStaffQueryResponse(final ForwardEvent event) {
//        staffTotalInfo = (StaffTotalInfo) event.getOrigin().getData();
//        if (null != staffTotalInfo) {
//            this.bean.getStaffCode().setValue(null);
//            this.bean.getStaffName().setValue(null);
//            staffTotalInfo.setStaffName(null);
//            staffTotalInfo.setStaffCode(null);
//        }
//        // 执行查询
//        onQuery();
//    }


    /**
     * 查询员工信息
     * 
     * @throws Exception
     *             异常
     */
    public void onQueryStaffTotalInfo() {
        int activePage = bean.getStaffTotalInfoListboxPaging().getActivePage();
        int pageSize = bean.getStaffTotalInfoListboxPaging().getPageSize();
        PageInfo pageInfo = staffAndOutStaffManager.queryPageInfoByStaffTotalInfo(staffTotalInfo, activePage + 1,
                pageSize);
        // 清单数据
        data = staffAndOutStaffManager.getStaffTotalInfoData(staffTotalInfo);
        // 总条数
        if(pageInfo !=null ) {
	        bean.getTotalSize().setValue(String.valueOf(pageInfo.getTotalCount()));
	        ListModel list = new BindingListModelList(pageInfo.getDataList(), true);
	        this.bean.getStaffTotalInfoListboxs().setModel(list);
	        this.bean.getStaffTotalInfoListboxPaging().setTotalSize(pageInfo.getTotalCount());
        }
    }

    /**
     * 每页显示事件
     */
    public void onPageSizeSelect() {
        if (this.bean.getPageListbox() != null && this.bean.getPageListbox().getSelectedItem().getValue() != null) {
            this.bean.getStaffTotalInfoListboxPaging().setActivePage(0);
            this.bean.getStaffTotalInfoListboxPaging()
                    .setPageSize(Integer.parseInt(this.bean.getPageListbox().getSelectedItem().getValue().toString()));
        }
        this.onQueryStaffTotalInfo();
    }

    /**
     * 翻页
     */
    public void onStaffTotalInfoListboxPaging() {
        onQueryStaffTotalInfo();
    }
    
    /**
     * 查询按钮
     * @throws Exception
     * @throws InterruptedException
     */
    public void onReportParametr() throws Exception, InterruptedException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("opType", "confirm");
        Window window = (Window) Executions.createComponents("/pages_nmg/advanceQuery/staffTotalReportPar_main.zul", null,
                map);
        window.doModal();
        window.addEventListener("onOK", new EventListener() {

            @Override
            public void onEvent(Event event) throws Exception {
                if (event.getData() != null) {
                    staffTotalInfo = (StaffTotalInfo) event.getData();
                    onQueryStaffTotalInfo();
                }
            }
        });
    }

    /**
     * 清单下载按钮
     * 
     * @throws Exception
     */
    public void onDownloadlist() throws Exception {
        if (data !=null && data.size() != 0) {
            // 设置字符集
            String charset = "UTF-8";
            String fileName = "人员信息总表_" + DateUtil.getYYYYMMDD(new Date());
            HttpServletRequest httpRequest = (HttpServletRequest) Executions.getCurrent().getNativeRequest();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ExportExcelNew.exportExcel("", data, os);
            byte[] content = os.toByteArray();
            String encodedName = null;
            encodedName = URLEncoder.encode(fileName + ".xlsx", charset);
            // 将空格替换为+号
            encodedName = encodedName.replace("%20", "+");
            // 解决ie6 bug 或者是火狐浏览器
            if (encodedName.length() > 150 || Servlets.isGecko(httpRequest) || Servlets.isGecko3(httpRequest)) {
                encodedName = new String(encodedName.getBytes(charset), "ISO8859-1");
            }
            Filedownload.save(content, "application/octet-stream", encodedName);
        } else {
            Messagebox.show("数据为空!");
            return;
        }
    }

    /**
     * 重置按钮
     */
    public void onReset() {
        clearVariable();
        this.bean.getTotalSize().setValue(null);
        ListboxUtils.clearListbox(this.bean.getStaffTotalInfoListboxs());
        this.bean.getStaffTotalInfoListboxPaging().setTotalSize(1);
        
        staffTotalInfo = new StaffTotalInfo();
    }

    /**
     * 清除变量
     */
    public void clearVariable() {
        staffTotalInfo = null;
        data.clear();
    }
}
